package gdut.imis.vo;

import com.alibaba.fastjson.annotation.JSONField;
import gdut.imis.domain.Manager;
import gdut.imis.domain.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author JiaFu
 * @Date 2023/4/11 13:07
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserLoginVo implements UserDetails {
    private User user;
    private Manager manager;
    private Boolean isManager;

    //    存储权限信息
    private List<String> permissions;

    //    存储SpringSecurity所需的权限信息的集合
    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    public UserLoginVo(User user, boolean isManager, List<String> permissions) {
        this.user = user;
        this.isManager = isManager;
        this.permissions = permissions;
    }

    public UserLoginVo(Manager manager, boolean isManager, List<String> permissions) {
        this.manager = manager;
        this.isManager = isManager;
        this.permissions = permissions;
    }

    public boolean isManager() {
        return isManager;
    }

    public void setIsManager(boolean isManager) {
        this.isManager = isManager;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) {
            return authorities;
        }
        if (permissions != null) {
            authorities = permissions.stream()
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        if (this.isManager) {
            return manager.getPassword();
        }
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        if (this.isManager) {
            return manager.getPhone();
        }
        return user.getIdCard();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
